package com.whmskj.xjlhsc.service;

import cn.hutool.extra.spring.SpringUtil;
import com.whmskj.xjlhbc.db.DataSourceType;
import com.whmskj.xjlhbc.db.DynamicDataSourceContextHolder;
import com.whmskj.xjlhsc.schedul.async.po.DbStateClass;
import com.whmskj.xjlhsc.service.dto.HumidificationRoomDto;
import com.whmskj.xjlhsc.service.dto.RealInfoDto;
import lombok.Data;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 实时监控接口服务层
 */

public interface MonitorService {

    Map<String, List<FieldDesc>> DESC_MAPPING = new ConcurrentHashMap<>();

    String ANNOTATION_SQL = """
            SELECT COLUMN_NAME AS fieldName,COLUMN_COMMENT AS fieldDesc
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA='xjsc' AND  TABLE_NAME = '%s';""";


    /**
     * 根据机台ID查询机台实时信息
     *
     * @param deviceId
     * @return
     */
    RealInfoDto getDeviceRealTimeInfo(Integer deviceId);


    /**
     * 获取字段描述
     *
     * @param fieldName
     * @param tb
     * @return
     */
    default String getObtainFieldDesc(String fieldName, String tb) {
        List<FieldDesc> fieldDescList = DESC_MAPPING.get(tb);
        if (fieldDescList == null) {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
            fieldDescList = Optional.of(SpringUtil.getBean(JdbcTemplate.class).query(String.format(ANNOTATION_SQL, tb), BeanPropertyRowMapper.newInstance(FieldDesc.class))).orElseGet(ArrayList::new);
            DESC_MAPPING.put(tb, fieldDescList);
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
        return fieldDescList.stream().filter(fieldDesc -> fieldDesc.getFieldName().equals(fieldName)).findFirst().map(FieldDesc::getFieldDesc).orElse("");
    }

    /**
     * 查询设备运行电能信息
     *
     * @param deviceId
     * @return
     */
    DbStateClass findDnInfo(Integer deviceId);

    /**
     * 查询加湿房实时数据
     * @param area 区域
     * @return
     */
    HumidificationRoomDto getHumidificationRoomRealData(String area);

    @Data
    class FieldDesc {
        private String fieldName;
        private String fieldDesc;
    }
}
